package com.xu.demo.controller;


import ch.qos.logback.core.util.FileUtil;
import com.xu.demo.common.R;
import com.xu.demo.entity.Post;
import com.xu.demo.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {
    @Value("${share1.datapath}")
    private  String fileUploadPath;

    @Autowired
    private PostService postService;
    @PostMapping("/upload")
    public R<Post> upload(@RequestParam("file") MultipartFile[] files) throws IOException {
        Post post = new Post();
        if (files.length == 1) {
            post.setGs(1L);
            String name = files[0].getOriginalFilename();
            String fileName = UUID.randomUUID().toString() + name;//dfsdfdfd.jpg]
            files[0].transferTo(new File(fileUploadPath + fileName));
            post.setZ1(name);
            post.setZl1(fileName);
        } else if (files.length == 2) {
            post.setGs(2L);
            String name0 = files[0].getOriginalFilename();
            String fileName0 = UUID.randomUUID().toString() + name0;
            files[0].transferTo(new File(fileUploadPath + fileName0));
            String name1 = files[1].getOriginalFilename();
            String fileName1 = UUID.randomUUID().toString() + name1;
            files[1].transferTo(new File(fileUploadPath + fileName1));
            post.setZ1(name0);
            post.setZl1(fileName0);
            post.setZ2(name1);
            post.setZl2(fileName1);
        }

        postService.save(post);
        System.out.println(post.toString());
        return R.success(post);
    }
}
